package com.lgl.controller;

import com.lgl.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable String email, @PathVariable String password,
        @PathVariable String code) {
        return userService.register(email, password, code);
    }

    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email) {
        return userService.isRegistered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response, @PathVariable String email, @PathVariable String password) {
        if (userService.login(email, password)) {
            Cookie userInfo = new Cookie("userInfo", email + password);
            response.addCookie(userInfo);
            return email;
        } else {
            return "";
        }
    }

    @GetMapping("/info/{token}")
    public String findEmail(@PathVariable String token) {
        return userService.findEmailByToken(token);
    }
}
